<?php
namespace app\controller;

use think\Request;
use think\facade\Db;
use think\facade\Cache;

class Login extends Common
{
	
	/**
	 * 登录接口
	 *
	 * @return
	 */
	public function index(Request $request)
	{
		$username = $request->param('username', '', 'trim');
		$password = $request->param('password', '', 'trim');
		$remember = $request->param('remember', '', 'trim');
		$captcha = $request->param('captcha', '', 'trim');
		$domain = $request->param('domain', '', 'trim');
		$token = $request->param('token', '', 'trim');
		$validate = new \app\validate\Login;
		$result = $validate->check(['domain' => $domain, 'username' => $username, 'password' => $password, 'captcha' => $captcha, 'token' => $token]);
		if ($result == false) {
			return json($validate->getError());
		}

		$cache = Cache::get($token, '');
		if( empty($cache) ) {
			return json(['msg' => '验证码错误!', 'access_token' => null, 'code' => 403, 'token_type' => null]);
		}

		if(!isset($cache['key'])) {
			return json(['msg' => '验证码错误!', 'access_token' => null, 'code' => 403, 'token_type' => null]);
		}

		if (!password_verify($captcha, $cache['key'])) {
			return json(['msg' => '验证码错误!', 'access_token' => null, 'code' => 403, 'token_type' => null]);
		}

		$query = Db::table('cfg_user')->field('id, companyId, username, password, company, level, nickname, status, expires, loginip, logintime, logincity')->where('username', $username)->find();
		if (!isset($query['id'])) {
			return json(['msg' => '用户名或密码错误!', 'access_token' => null, 'code' => 403, 'token_type' => null]);
		}

		if (!password_verify($password, $query['password'])) {
			$this->cfg_write_logs($request, $token, $query['companyId'], $query['nickname'], $query['username'], 1);
			return json(['msg' => '用户名或密码错误!', 'access_token' => null, 'code' => 403, 'token_type' => null]);
		}

		if( $query['status'] <> 1 ) {
			$this->cfg_write_logs($request, $token, $query['companyId'], $query['nickname'], $query['username'], 1);
			return json(['msg' => '账户以被锁定, 请联系管理员!', 'access_token' => null, 'code' => 403, 'token_type' => null]);
		}
		
		$company = $query['company'];
		$expires = $query['expires'];
		
		if( $query['expires'] > '2000-01-01 08:00:00') {
			if( $query['level'] == 2 ) {
				if( date('Y-m-d H:i:s') >= $query['expires'] ){
					return json(['msg' => '账户已过期, 请联系管理员!', 'access_token' => null, 'code' => 403, 'token_type' => null]);
				}
			}
			if( $query['level'] == 3 ) {
				$subquery = Db::table('cfg_user')->field('id, company, expires')->where('companyId', $query['companyId'])->where('level', 2)->find();
				if( !isset($subquery['id']) ) {
					return json(['msg' => '主账号存在异常, 请联系管理员!', 'access_token' => null, 'code' => 403, 'token_type' => null]);
				}
				if( date('Y-m-d H:i:s') >= $subquery['id'] ) {
					$company = $subquery['company'];
					$expires = $subquery['expires'];
					return json(['msg' => '主账户已过期, 请联系管理员!', 'access_token' => null, 'code' => 403, 'token_type' => null]);
				}
			}
		}

		if( $query['loginip'] ) {
			$temp1 = explode('.', $this->GetIP());
			$temp2 = "{$temp1[0]}.{$temp1[1]}.{$temp1[2]}";
			if( stripos($query['loginip'], $temp2) === false ) {
				$this->cfg_write_logs($request, $token, $query['companyId'], $query['nickname'], $query['username'], 1);
				return json(['msg' => '未授权IP禁止登录, 请联系管理员!', 'access_token' => null, 'code' => 403, 'token_type' => null]);
			}
		}

		if( $query['logintime'] ) {
			$temp1 = explode('-', $query['logintime']);
			if(date('G') < $temp1[0] || date('G') > $temp1[1] ){
				$this->cfg_write_logs($request, $token, $query['companyId'], $query['nickname'], $query['username'], 1);
				return json(['msg' => '当前时段未授权登录, 请联系管理员!', 'access_token' => null, 'code' => 403, 'token_type' => null]);
			}
		}

		if( $query['logincity'] ) {
			$logincity = explode(',', $query['logincity']);
			$address = new \Net\IpLocation( app()->getRootPath() . 'data' . DIRECTORY_SEPARATOR . 'qqwry.dat');
			$addressName = $address->getAddrName($this->GetIP());
			foreach ($logincity as $value) {
				if( stripos($addressName, $value) !== false ) {
					$this->cfg_write_logs($request, $token, $query['companyId'], $query['nickname'], $query['username'], 1);
					return json(['msg' => '不在常用登录地登录, 请回到常用登录地登录!', 'access_token' => null, 'code' => 403, 'token_type' => null]);
				}
			}
		}

		Cache::set($token, ['id'=> $query['id'], 'companyId'=> $query['companyId'], 'level'=> $query['level'], 
		  'username'=> $query['username'], 'nickname'=> $query['nickname'], 'company'=> $company ? $company : '未设置', 'expires'=> $expires ? $expires : '永不过期'], 30 * 86400);

		Db::name('cfg_user')->where('id', $query['id'])->where('companyId', $query['companyId'])->update([ 'lasttime' => time(), 'lastip' => $this->GetIP() ]);

		$this->cfg_write_logs($request, $token, $query['companyId'], $query['nickname'], $query['username'], 0);

		return json(['msg' => '登录成功!', 'access_token' => $token, 'code' => 0, 'token_type' => 'Bearer']);

	}

}
